<template>
  <div class="kras_markdown_wrap">
    <div class="content">
      <h1>{{ articleTitle }}</h1>
      <div
        class="markdown-body"
        ref="HighlightRef"
        v-highlight
        v-html="articleHtml"
      ></div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from "vue";
import "./markdown.scss";
import "./one-dark-pro.scss";
import "./index.scss";
export default defineComponent({
  name: "v-kras-markdown",
});
</script>
<script setup>
import axios from "axios";
import { marked } from "marked";
import { addCopyButton } from "../../utils/highlight";

/* options    // 组件选项
   {
      // 类型 'md'-md文件,'html_content'-html内容
      type:"",
      // 标题
      title:"",
      // md文件链接(type='md'时有效)
      mdFileUrl:"",
      // html内容(type='html_content'时有效)
      htmlContent:"",
   }
*/

// props
const props = defineProps(["options"]);

// emits
const emits = defineEmits(["codeBoxCopySuccess"]);

// title
const articleTitle = ref("");

// html_content
const articleHtml = ref("");

// HighlightRef
const HighlightRef = ref(null);

const getArticleDetail = async (url) => {
  const res = await axios.get(url);
  articleTitle.value = res.data.data.title;
  articleHtml.value = res.data.data.html_content;
};

const getMarkDownFile = async (url) => {
  const res = await axios.get(url);
  articleHtml.value = marked(res.data);
};

// markdown init
const markDownInit = () => {
  // content dispose
  let { type, title, mdFileUrl, htmlContent } = props.options;

  articleTitle.value = title;
  switch (type) {
    case "md":
      getMarkDownFile(mdFileUrl);
      break;

    case "html_content":
      articleHtml.value = htmlContent;
      break;

    default:
      break;
  }

  // btn
  setTimeout(() => {
    let el = HighlightRef.value;
    const blocks = Array.from(HighlightRef.value.querySelectorAll("pre code"));
    blocks.forEach((block) =>
      addCopyButton(block, () => {
        emits("codeBoxCopySuccess");
      })
    );
  }, 200);
};

// init
onMounted(() => {
  // getArticleDetail("http://47.92.246.66:1112/markdown/mongodb.json");
  // getMarkDownFile("http://47.92.246.66:1112/markdown/package_flow.md");
  markDownInit();
});
</script>

<style lang="scss" scoped></style>
